// src/main/services/log.service.ts
import { Injectable } from '@nestjs/common'
import { dirname, join } from 'path'
import fs from 'fs'
import log from 'electron-log'
import { app } from 'electron'

@Injectable()
export class LogService {
  constructor() {
    // 日志目录和文件名配置
    const baseDir = app.isPackaged ? dirname(process.execPath) : app.getAppPath()
    const logsDir = join(baseDir, 'logs')
    if (!fs.existsSync(logsDir)) {
      fs.mkdirSync(logsDir, { recursive: true })
    }
    const date = new Date()
    const yyyy = date.getFullYear()
    const mm = String(date.getMonth() + 1).padStart(2, '0')
    const dd = String(date.getDate()).padStart(2, '0')
    const datedName = `main-${yyyy}-${mm}-${dd}.log`
    Object.assign(log.transports.file, {
      resolvePathFn: () => join(logsDir, datedName),
      maxSize: 10 * 1024 * 1024
    })
    log.transports.file.level = 'info'
    log.transports.console.level = 'info'
    log.initialize({ preload: true })

    // 控制台格式
    ;(log.transports.console as any).format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}'
    ;(log.transports.console as any).useStyles = false
    ;(log.transports.console as any).useColors = true

    // 初始化日志
    const resolvedPath =
      (log.transports.file as any).getFile?.().path ||
      (log.transports.file as any).resolvePathFn?.()
    log.info('日志初始化完成，文件：', resolvedPath)
    console.log('✅ LogService 构造函数执行')
  }

  info(message: string, ...args: any[]) {
    console.info(`[Main] ${message}`, ...args)
    log.info(message, ...args)
  }

  warn(message: string, ...args: any[]) {
    console.warn(`[Main] ${message}`, ...args)
    log.warn(message, ...args)
  }

  error(message: string, ...args: any[]) {
    console.error(`[Main] ERROR: ${message}`, ...args)
    log.error(message, ...args)
  }
}
